<template>
  <div class="roles-page">
    <div class="container">
      <div class="page-header">
        <h1 class="page-title">角色广场</h1>
        <p class="page-subtitle">发现各种有趣的AI角色，开始你的专属对话</p>
      </div>
      
      <div class="search-section">
        <div class="search-bar">
          <input 
            v-model="searchKeyword" 
            @keyup.enter="searchRoles"
            placeholder="搜索角色名称或标签..." 
            class="search-input"
          />
          <button @click="searchRoles" class="search-btn">
            <span class="search-icon">🔍</span>
            搜索
          </button>
        </div>
        
        <div class="filters">
          <select v-model="selectedStatus" @change="searchRoles" class="filter-select">
            <option value="">全部状态</option>
            <option value="PUBLISHED">已发布</option>
            <option value="DRAFT">草稿</option>
          </select>
          
          <select v-model="selectedPrivacy" @change="searchRoles" class="filter-select">
            <option value="">全部类型</option>
            <option value="PUBLIC">公开</option>
            <option value="PRIVATE">私有</option>
          </select>
          
          <select v-model="selectedSort" @change="searchRoles" class="filter-select">
            <option value="createdAt">最新创建</option>
            <option value="usageCount">使用次数</option>
            <option value="averageRating">评分最高</option>
            <option value="shareCount">分享最多</option>
          </select>
        </div>
      </div>
      
      <div v-if="loading" class="loading-grid">
        <div v-for="i in 12" :key="i" class="role-card skeleton">
          <div class="skeleton-avatar"></div>
          <div class="skeleton-content">
            <div class="skeleton-title"></div>
            <div class="skeleton-desc"></div>
            <div class="skeleton-stats"></div>
          </div>
        </div>
      </div>
      
      <div v-else-if="roles.length === 0" class="empty-state">
        <div class="empty-icon">🤖</div>
        <h3>暂无角色</h3>
        <p>没有找到符合条件的角色，试试调整搜索条件</p>
        <button @click="resetFilters" class="reset-btn">重置筛选</button>
      </div>
      
      <div v-else class="roles-grid">
        <div 
          v-for="role in roles" 
          :key="role.id" 
          class="role-card"
          @click="startChat(role)"
        >
          <div class="role-avatar">
            <img v-if="role.avatarUrl" :src="role.avatarUrl" :alt="role.name" />
            <div v-else class="avatar-placeholder">{{ role.name.charAt(0) }}</div>
            <div class="role-status" :class="role.status.toLowerCase()">
              {{ getStatusText(role.status) }}
            </div>
          </div>
          
          <div class="role-info">
            <h3 class="role-name">{{ role.name }}</h3>
            <p class="role-desc">{{ role.description || '暂无描述' }}</p>
            
            <div class="role-tags" v-if="role.tags">
              <span 
                v-for="tag in getTags(role.tags)" 
                :key="tag" 
                class="tag"
              >
                {{ tag }}
              </span>
            </div>
            
            <div class="role-stats">
              <div class="stat">
                <span class="stat-icon">💬</span>
                <span class="stat-value">{{ role.usageCount || 0 }}</span>
                <span class="stat-label">使用</span>
              </div>
              <div class="stat">
                <span class="stat-icon">⭐</span>
                <span class="stat-value">{{ role.averageRating || 0 }}</span>
                <span class="stat-label">评分</span>
              </div>
              <div class="stat">
                <span class="stat-icon">📅</span>
                <span class="stat-value">{{ formatDate(role.createdAt) }}</span>
              </div>
            </div>
          </div>
          
          <div class="role-actions">
            <button class="chat-btn">开始对话</button>
            <button class="favorite-btn" @click.stop="toggleFavorite(role)">
              <span class="favorite-icon">{{ isFavorite(role.id) ? '❤️' : '🤍' }}</span>
            </button>
          </div>
        </div>
      </div>
      
      <div v-if="hasMore && !loading" class="load-more">
        <button @click="loadMore" class="load-more-btn">加载更多</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'

const router = useRouter()
const route = useRoute()

const loading = ref(false)
const roles = ref([])
const hasMore = ref(true)
const pageNo = ref(1)
const pageSize = 12

const searchKeyword = ref('')
const selectedStatus = ref('')
const selectedPrivacy = ref('')
const selectedSort = ref('createdAt')

const favorites = ref(new Set())

const loadRoles = async (reset = false) => {
  if (loading.value) return
  
  if (reset) {
    pageNo.value = 1
    roles.value = []
    hasMore.value = true
  }
  
  if (!hasMore.value) return
  
  loading.value = true
  
  try {
    const token = localStorage.getItem('auth_token')
    const headers = token ? { 'Authorization': `Bearer ${token}` } : {}
    
    const params = new URLSearchParams({
      pageNo: pageNo.value.toString(),
      pageSize: pageSize.toString(),
      sortBy: selectedSort.value,
      asc: 'false'
    })
    
    if (searchKeyword.value) params.set('keyword', searchKeyword.value)
    if (selectedStatus.value) params.set('status', selectedStatus.value)
    if (selectedPrivacy.value) params.set('privacy', selectedPrivacy.value)
    
    const res = await fetch(`/api/roles/search?${params.toString()}`, { headers })
    const data = await res.json()
    
    const newRoles = data.data?.records || []
    if (newRoles.length < pageSize) {
      hasMore.value = false
    }
    
    if (reset) {
      roles.value = newRoles
    } else {
      roles.value = [...roles.value, ...newRoles]
    }
    
    pageNo.value++
  } catch (e) {
    console.error('加载角色失败', e)
  } finally {
    loading.value = false
  }
}

const searchRoles = () => {
  loadRoles(true)
}

const loadMore = () => {
  loadRoles(false)
}

const resetFilters = () => {
  searchKeyword.value = ''
  selectedStatus.value = ''
  selectedPrivacy.value = ''
  selectedSort.value = 'createdAt'
  loadRoles(true)
}

const startChat = async (role) => {
  try {
    const token = localStorage.getItem('auth_token')
    if (!token) {
      router.push('/login')
      return
    }
    
    // 创建新会话
    const res = await fetch('/api/conversations', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        roleId: role.id,
        roleVersion: 'latest'
      })
    })
    
    if (res.ok) {
      const data = await res.json()
      if (data.code === 0) {
        const conversationId = data.data
        
        // 增加角色使用量
        try {
          await fetch(`/api/roles/${role.id}/use`, {
            method: 'POST',
            headers: {
              'Authorization': `Bearer ${token}`
            }
          })
        } catch (e) {
          console.warn('增加使用量失败', e)
        }
        
        // 跳转到聊天页面
        router.push({ path: `/chat/${role.id}`, query: { conversationId } })
      } else {
        alert('创建会话失败：' + data.message)
      }
    } else {
      alert('创建会话失败，请重试')
    }
  } catch (e) {
    console.error('创建会话失败', e)
    alert('创建会话失败，请重试')
  }
}

const toggleFavorite = (role) => {
  if (favorites.value.has(role.id)) {
    favorites.value.delete(role.id)
  } else {
    favorites.value.add(role.id)
  }
  // TODO: 调用后端API保存收藏状态
}

const isFavorite = (roleId) => {
  return favorites.value.has(roleId)
}

const getStatusText = (status) => {
  const statusMap = {
    'PUBLISHED': '已发布',
    'DRAFT': '草稿',
    'PENDING': '待审核',
    'REJECTED': '已拒绝'
  }
  return statusMap[status] || status
}

const getTags = (tags) => {
  if (!tags) return []
  return tags.split(',').slice(0, 3) // 最多显示3个标签
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const now = new Date()
  const diffTime = Math.abs(now - date)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays === 1) return '昨天'
  if (diffDays < 7) return `${diffDays}天前`
  if (diffDays < 30) return `${Math.ceil(diffDays / 7)}周前`
  return date.toLocaleDateString()
}

// 监听路由变化
watch(() => route.query, (newQuery) => {
  if (newQuery.keyword) {
    searchKeyword.value = newQuery.keyword
  }
  if (newQuery.category) {
    // 可以根据分类设置筛选条件
  }
  loadRoles(true)
}, { immediate: true })

onMounted(() => {
  loadRoles(true)
})
</script>

<style scoped>
.roles-page {
  height: 100%;
  background: #f8fafc;
  padding: 40px 0;
  overflow-y: auto;
}

.container {
  width: 100%;
  padding: 0 32px;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: #1f2937;
  margin-bottom: 8px;
}

.page-subtitle {
  font-size: 1.125rem;
  color: #6b7280;
}

.search-section {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.05);
  margin-bottom: 32px;
}

.search-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
  padding: 12px 16px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.2s;
}

.search-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.search-btn {
  padding: 12px 20px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.filters {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.filter-select {
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  background: white;
  font-size: 14px;
  cursor: pointer;
}

.roles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 24px;
  margin-bottom: 40px;
}

.role-card {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.05);
  border: 1px solid #e5e7eb;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.role-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 24px rgba(0,0,0,0.1);
  border-color: #667eea;
}

.role-avatar {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-bottom: 16px;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea, #764ba2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.role-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  color: white;
  font-size: 32px;
  font-weight: 600;
}

.role-status {
  position: absolute;
  top: -4px;
  right: -4px;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  color: white;
}

.role-status.published {
  background: #10b981;
}

.role-status.draft {
  background: #f59e0b;
}

.role-status.pending {
  background: #3b82f6;
}

.role-name {
  font-size: 1.25rem;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 8px;
}

.role-desc {
  color: #6b7280;
  line-height: 1.5;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.role-tags {
  display: flex;
  gap: 6px;
  margin-bottom: 16px;
  flex-wrap: wrap;
}

.tag {
  background: #f3f4f6;
  color: #374151;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.role-stats {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}

.stat {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #6b7280;
  font-size: 14px;
}

.stat-icon {
  font-size: 16px;
}

.stat-value {
  font-weight: 500;
}

.stat-label {
  font-size: 12px;
}

.role-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.chat-btn {
  flex: 1;
  padding: 10px 16px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.chat-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.favorite-btn {
  padding: 10px;
  background: #f3f4f6;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.favorite-btn:hover {
  background: #e5e7eb;
}

.favorite-icon {
  font-size: 18px;
}

.load-more {
  text-align: center;
}

.load-more-btn {
  padding: 12px 24px;
  background: white;
  color: #667eea;
  border: 2px solid #667eea;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.load-more-btn:hover {
  background: #667eea;
  color: white;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #6b7280;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 16px;
}

.empty-state h3 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #374151;
  margin-bottom: 8px;
}

.reset-btn {
  margin-top: 16px;
  padding: 10px 20px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.reset-btn:hover {
  background: #5a67d8;
}

.loading-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
  margin-bottom: 40px;
}

.skeleton {
  background: white;
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 6px rgba(0,0,0,0.05);
  border: 1px solid #e5e7eb;
}

.skeleton-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: #e5e7eb;
  margin-bottom: 16px;
  animation: pulse 2s infinite;
}

.skeleton-content {
  flex: 1;
}

.skeleton-title {
  height: 20px;
  background: #e5e7eb;
  border-radius: 4px;
  margin-bottom: 8px;
  animation: pulse 2s infinite;
}

.skeleton-desc {
  height: 16px;
  background: #e5e7eb;
  border-radius: 4px;
  margin-bottom: 8px;
  animation: pulse 2s infinite;
}

.skeleton-stats {
  height: 16px;
  background: #e5e7eb;
  border-radius: 4px;
  width: 60%;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

@media (max-width: 768px) {
  .roles-grid {
    grid-template-columns: 1fr;
  }
  
  .search-bar {
    flex-direction: column;
  }
  
  .filters {
    flex-direction: column;
  }
  
  .role-stats {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
